package com.wifi.eshipewifi;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.okhttp.Request;
import com.wifi.BaseApplication;
import com.wifi.imp.MessageListener;
import com.wifi.imp.MessageSend;
import com.wifi.utils.WifiUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

public class RouterSettingActivity extends AppCompatActivity implements View.OnClickListener,MessageListener {
    ImageButton ib_back;
    ImageView iv_toast;
    TextView tv_include_tittle;
    TextView tv_black;
    LinearLayout ll_reboot;
    LinearLayout ll_update;
    BaseApplication application;
    String TAG="RouterSettingActivity";
    LinearLayout ll_background;
    LinearLayout ll_toast;
    boolean toastState;
    SharedPreferences sp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_router_setting);

        //每个activity都要加这一句
        application = (BaseApplication) getApplication();
        sp= getSharedPreferences("wifiSetting", Activity.MODE_PRIVATE);
        toastState = sp.getBoolean("toastState", false);

        ll_background = (LinearLayout) findViewById(R.id.ll_background);
        ll_toast = (LinearLayout) findViewById(R.id.ll_toast);
        tv_black = (TextView) findViewById(R.id.tv_black);
        tv_include_tittle = (TextView) findViewById(R.id.tv_include_tittle);
        iv_toast = (ImageView) findViewById(R.id.iv_toast);
        ib_back = (ImageButton) findViewById(R.id.ib_back);
        ll_update = (LinearLayout) findViewById(R.id.ll_update);
        ll_reboot = (LinearLayout) findViewById(R.id.ll_reboot);
        tv_include_tittle.setText("路由器管理");
        if(toastState){
            iv_toast.setBackgroundResource(R.drawable.open);
        }else {
            iv_toast.setBackgroundResource(R.drawable.close);
        }
        ib_back.setOnClickListener(this);
        ll_update.setOnClickListener(this);
        ll_reboot.setOnClickListener(this);
        iv_toast.setOnClickListener(this);
    }

    @Override
    protected void onResume() {//每个activity都要加这一句
        super.onResume();
        if(application==null)
            application = (BaseApplication) getApplication();
        application.setMsgListener(this);
    }

    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==0){
                String lastUpdate = application.getLastUpdate();
                if(reallyFileName!=null){//判断固件版本
// todo                    if( reallyFileName.equals(lastUpdate)){
//                        Toast.makeText(RouterSettingActivity.this,"当前版本为最新版本，无需更新",Toast.LENGTH_SHORT).show();
//                    }else {//版本下载并更新
                        ll_background.setVisibility(View.VISIBLE);
                        tv_black.setText("正在更新中，请稍等……");
                        application.makeToast(RouterSettingActivity.this,"正在下载中",true);
                        OkHttpUtils
                                .get()
                                .url(url)
                                .build()
                                .execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), reallyFileName)
                                {
                                    @Override
                                    public void inProgress(float progress)
                                    {
                                    }

                                    @Override
                                    public void onError(Request request, Exception e)
                                    {
                                        Log.e(TAG, "onError :" + e.getMessage());
                                        application.makeToast(RouterSettingActivity.this,"下载失败"+e.getMessage(),true);
                                    }

                                    @Override
                                    public void onResponse(File file)
                                    {
                                        Log.e(TAG, "onResponse :" + file.getAbsolutePath());
                                        long length = file.length();
                                        absolutePath=file.getAbsolutePath();
                                        application.makeToast(RouterSettingActivity.this,"下载成功",true);
                                        application.sendMsg("$file;"+reallyFileName+";"+String.valueOf(length)+";");
                                        application.setLastUpdate(reallyFileName);//设置本次更新的固件名
                                    }
                                });

//todo                    }
                }

            }
        }
    };

    String reallyFileName;
    /**
     * 网络操作相关的子线程
     */
    Runnable networkTask = new Runnable() {

        @Override
        public void run() {
            // TODO
            reallyFileName = url;
            reallyFileName = getReallyFileName(url);
//            int num = reallyFileName.indexOf("filename");
//            reallyFileName=reallyFileName.substring(num+10,num+24);
            reallyFileName="upgrade.bin";
//            String[] split = reallyFileName.split("/");
//            reallyFileName = split[1].trim().substring(10, 24);
//            reallyFileName = split[2];
            handler.sendEmptyMessage(0);
        }
    };


//    String url="http://192.168.1.106:280/openwrt/sysupgrade.bin";//http://www.starnet.cc:280  chinajiaxing.gicp.net:821
    String url="http://106.14.61.174:4399/mobang_upgrade/sysupgrade.bin";//http://www.starnet.cc:280  chinajiaxing.gicp.net:821
//    String url="http://192.168.1.106:280/mobang/upgrade.bin";//http://www.starnet.cc:280  chinajiaxing.gicp.net:821
    String absolutePath;
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ib_back:
                this.finish();
                break;

            case R.id.iv_toast:
                SharedPreferences.Editor edit = sp.edit();
                if(toastState){//关闭
                    toastState=false;
                    iv_toast.setBackgroundResource(R.drawable.close);
                    application.makeToast(RouterSettingActivity.this,"关闭成功",true);
                }else {
                    toastState=true;
                    iv_toast.setBackgroundResource(R.drawable.open);
                    application.makeToast(RouterSettingActivity.this,"开启成功",true);
                }
                edit.putBoolean("toastState",toastState);
                edit.commit();
                break;

            case R.id.ll_reboot:
                if(application!=null){
                    ll_background.setVisibility(View.VISIBLE);
                    application.sendMsg("$reboot;");
                }
                break;

            case R.id.ll_update:
                final View view = View.inflate(this, R.layout.item_dialog_update_text, null);
                AlertDialog dialog= new AlertDialog.Builder(this)
                        .setTitle("更新")
                        .setIcon(android.R.drawable.ic_dialog_info)
                        .setView(view)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                new Thread(networkTask).start();//首先获取固件名称
                                dialog.cancel();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        }).create();
                dialog .show();
                break;
        }
    }

    @Override
    public void MessageGetListener(String msg) {
        try {
            if (msg != null) {
                String s = msg;
                application.makeToast(RouterSettingActivity.this,s,false);
                if (s.trim().length() > 0) {
                    Log.i(TAG, "mhandler接收到obj=" + s);
                    String s1[]=s.split(";");
                    if(s1[0].indexOf("reboot")!=-1){//打开
                        application.makeToast(RouterSettingActivity.this,s,false);

                        //断线重连
                        String ssid = application.getSsid();
                        String password = application.getPassword();
                        WifiUtils wifiUtils=new WifiUtils(RouterSettingActivity.this);
                        wifiUtils.WifiRebootForSetName(RouterSettingActivity.this,application,ssid,password);
                    }else if(s1[0].indexOf("first_connect")!=-1){
                        application.makeToast(RouterSettingActivity.this,"连接成功",true);
                        ll_background.setVisibility(View.GONE);
                    }else if(s1[1].indexOf("file_can_transfer")!=-1){
                        if(absolutePath!=null){
                            boolean isSend = application.sendFile(absolutePath);
//                            if(isSend){
//                                application.makeToast(RouterSettingActivity.this,"文件发送成功");
//                            }else {
//                                application.makeToast(RouterSettingActivity.this,"文件发送失败");
//                            }
                        }

                    }else if(s1[1].indexOf("file_received")!=-1){
                        application.makeToast(RouterSettingActivity.this,"文件发送成功",true);
                        ll_background.setVisibility(View.GONE);
                    }
                }
            }
        } catch (Exception ee) {
            Log.i(TAG, "加载过程出现异常");
            ee.printStackTrace();
        }
    }

    public static String getReallyFileName(String url) {
        String filename = "";
        URL myURL;
        HttpURLConnection conn = null;
        if (url == null || url.length() < 1) {
            return null;
        }

        try {
            myURL = new URL(url);
            conn = (HttpURLConnection) myURL.openConnection();
            conn.connect();
            conn.getResponseCode();
            URL absUrl = conn.getURL();// 获得真实Url
            Log.e("H3c", "x:" + absUrl);
            // 打印输出服务器Header信息
            // Map<String, List<String>> map = conn.getHeaderFields();
            // for (String str : map.keySet()) {
            // if (str != null) {
            // Log.e("H3c", str + map.get(str));
            // }
            // }
            filename = conn.getHeaderField("Content-Disposition");// 通过Content-Disposition获取文件名，这点跟服务器有关，需要灵活变通
            if (filename == null || filename.length() < 1) {
                filename = absUrl.getFile();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }

        return filename;
    }



}
